//
//  AddLiving_ViewController.m
//  MZSystem
//
//  Created by 智障 on 2018/11/5.
//  Copyright © 2018 zerod. All rights reserved.
//

#import "AddLiving_ViewController.h"

#import "AddLivingPerson_ViewController.h"

#import "AddLiveView.h"
#import "TXTimeSelectorViewController.h"

@interface AddLiving_ViewController ()<UIAlertViewDelegate>
@property (nonatomic ,strong) Base_CenterNavView *navView;
@property (nonatomic ,strong) AddLiveView        *addDetailView;
@property (nonatomic ,strong) UIScrollView       *scrollView;

@property (nonatomic ,assign) BOOL                isStart;
@end

@implementation AddLiving_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.navView];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.addDetailView];
    if (self.model) {
        self.addDetailView.model = self.model;
    }else{
        self.model = [LiveDetailModel new];
        self.addDetailView.model = self.model;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.model) {
        [self.addDetailView reloadData];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [SVProgressHUD dismiss];
}
-(UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,SafeAreaTopHeight,ScrW,ScrH - SafeAreaTopHeight - SafeAreaBottomHeight)];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.contentSize = CGSizeMake(ScrW, 780.f);
    }
    return _scrollView;
}
- (AddLiveView *)addDetailView{
    if (!_addDetailView) {
        _addDetailView = [Base_loadXibView loadFromXib:@"AddLiveView" withCls:[AddLiveView class]];
        [_addDetailView setFrame:CGRectMake(0, 0, ScrW, 780.f)];
        WS(weakSelf)
        _addDetailView.bgViewClick = ^{
            [weakSelf chooseCover];
        };
        _addDetailView.timeClick = ^(BOOL isStart) {
            weakSelf.isStart = isStart;
            [weakSelf presentDateTime];
        };
        _addDetailView.scrollViewClick = ^(NSInteger tag) {
            for (id tf in weakSelf.addDetailView.subviews) {
                if ([tf isKindOfClass:[UITextField class]]) {
                    UITextField *textField = (UITextField *)tf;
                    [textField resignFirstResponder];
                }
            }
            AddLivingPerson_ViewController *vc = [AddLivingPerson_ViewController new];
            vc.tag = tag;
            vc.model = weakSelf.model;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _addDetailView;
}
- (void)chooseCover{
    WS(weakSelf)
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
        photoController.selectPhotoOfMax = 1;
        [photoController showIn:weakSelf result:^(id responseObject){
            NSArray *photos = (NSArray *)responseObject;
            ZZPhoto *photo = photos[0];
            self.model.image =  photo.originImage;
            self.model.cover = @"";
            [self.addDetailView.bgImageButton setImage:photo.originImage forState:UIControlStateNormal];
            self.addDetailView.addImage.hidden = YES;
            self.addDetailView.addLabel.hidden = YES;
        }];
    }];
    UIAlertAction *ceramAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZZCameraController *cameraController = [[ZZCameraController alloc]init];
        cameraController.takePhotoOfMax = 1;
        cameraController.isSaveLocal = NO;
        [cameraController showIn:weakSelf result:^(id responseObject){
            NSArray *photos = (NSArray *)responseObject;
            ZZCamera *camera = photos[0];
            self.model.image =  camera.image;
            self.model.cover = @"";
            [self.addDetailView.bgImageButton setImage:camera.image forState:UIControlStateNormal];
            self.addDetailView.addImage.hidden = YES;
            self.addDetailView.addLabel.hidden = YES;
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:photoAction];
    [alertController addAction:ceramAction];
    [alertController addAction:cancelAction];
    
    // 出现
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
- (void)presentDateTime{
    WS(weakSelf)
    TXTimeSelectorViewController *tc = [[TXTimeSelectorViewController alloc]initWithShowFrame:CGRectMake(0, SCREEN_HEIGHT - (SCREEN_HEIGHT/2),SCREEN_WIDTH , SCREEN_HEIGHT/2) ShowStyle:MYPresentedViewShowStyleFromBottomSpreadStyle callback:^(NSString  *result) {
        if (weakSelf.isStart) {
            NSString *beginT = [weakSelf getTimeStrWithString:result];
            if ([weakSelf.model.endTime doubleValue] == 0) {
                weakSelf.model.beginTime = beginT;
                weakSelf.addDetailView.beginTimeL.text = [result substringWithRange:NSMakeRange(5, result.length - 5)];
                return ;
            }
            if ([beginT doubleValue] < [weakSelf.model.endTime doubleValue]) {
                weakSelf.model.beginTime = beginT;
                weakSelf.addDetailView.beginTimeL.text = [result substringWithRange:NSMakeRange(5, result.length - 5)];
            }else{
                SHOWERROR(@"起止时间应小于结束时间")
            }
            
        }else{
            NSString *endT = [weakSelf getTimeStrWithString:result];
            if ([weakSelf.model.beginTime doubleValue] == 0) {
                weakSelf.addDetailView.endTimeL.text = [result substringWithRange:NSMakeRange(5, result.length - 5)];
                weakSelf.model.endTime = endT;
                return;
            }
            if ([weakSelf.model.beginTime doubleValue] < [endT doubleValue]) {
                weakSelf.addDetailView.endTimeL.text = [result substringWithRange:NSMakeRange(5, result.length - 5)];
                weakSelf.model.endTime = endT;
            }else{
                SHOWERROR(@"起止时间应小于结束时间")
            }
        }
    }];
    tc.mode = UIDatePickerModeDateAndTime;
    [self presentViewController:tc animated:YES completion:nil];
}
- (NSString *)getTimeStrWithString:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}
- (Base_CenterNavView *)navView{
    if (!_navView) {
        _navView = [Base_loadXibView loadFromXib:@"Base_CenterNavView" withCls:[Base_CenterNavView class]];
        [_navView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SafeAreaTopHeight)];
        _navView.navTitle.text = self.isModify ? @"修改直播" : @"创建直播";
        
        _navView.rightbutton.hidden = NO;
        [_navView.rightbutton setTitle:@"保存" forState:UIControlStateNormal];
        WS(weakSelf)
        _navView.clickBack = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        _navView.clickRightBtn = ^{
            [weakSelf saveNewLiving];
        };
    }
    return _navView;
}
- (void)saveNewLiving{
    if (self.addDetailView.titleTF.text.length == 0) {
        SHOWERROR(@"请输入标题")return;
    }
    if (self.model.beginTime == 0 || self.model.endTime == 0 ) {
        SHOWERROR(@"请选择直播时间")return;
    }
    if (self.addDetailView.reporterTF.text.length == 0) {
        SHOWERROR(@"请输入发布者")return;
    }
    if (self.model.streamUsers.length == 0) {
        SHOWERROR(@"请输入直播员")return;
    }
    NSString *title = self.addDetailView.titleTF.text;
    NSString *reporter = self.addDetailView.reporterTF.text;
    [SVProgressHUD show];
    self.navView.rightbutton.enabled = NO;
    if (self.model.image) {
        [self uploadImageWithData:self.model.image withSuccessBlock:^(NSString *imageUrl) {
            [self addOrModifyMsgWithTitle:title withReporter:reporter withImgUrl:imageUrl];
        }];
    }else{
        [self addOrModifyMsgWithTitle:title withReporter:reporter withImgUrl:nil];
    }
}
- (void)addOrModifyMsgWithTitle:(NSString *)title withReporter:(NSString *)reporter withImgUrl:(NSString *)imgUrl{
    NSString *url;
    NSMutableDictionary *paramDic = [NSMutableDictionary new];
    if (self.isModify) {
        url = [NSString stringWithFormat:@"%@/api/live/edit",URL_HOST];
        [paramDic setObject:self.model.id forKey:@"projectId"];
    }else{
        url = [NSString stringWithFormat:@"%@/api/live/new",URL_HOST];
    }
    [paramDic setObject:@"0" forKey:@"videoType"];
    [paramDic setObject:@"1" forKey:@"depUuid"];
    if (imgUrl.length > 0) {
        [paramDic setObject:imgUrl forKey:@"cover"];
    }
    if (self.model.cover.length > 0) {
        [paramDic setObject:self.model.cover forKey:@"cover"];
    }
    if (title.length > 0) {
        [paramDic setObject:title forKey:@"title"];
    }
    if (self.model.beginTime.length > 0) {
        [paramDic setObject:self.model.beginTime forKey:@"beginTime"];
    }
    if (self.model.endTime.length > 0) {
        [paramDic setObject:self.model.endTime forKey:@"endTime"];
    }
    if (reporter.length > 0) {
        [paramDic setObject:reporter forKey:@"reporter"];
    }
    if (self.model.streamUsers.length > 0) {
        [paramDic setObject:self.model.streamUsers forKey:@"streamUsers"];
    }
    if (self.model.reporters.length > 0) {
        [paramDic setObject:self.model.reporters forKey:@"reporters"];
    }
    if (self.model.directors.length > 0) {
        [paramDic setObject:self.model.directors forKey:@"directors"];
    }
    if (self.model.editors.length > 0) {
        [paramDic setObject:self.model.editors forKey:@"editors"];
    }
    if (self.addDetailView.introTF.text.length > 0) {
        [paramDic setObject:self.addDetailView.introTF.text forKey:@"intro"];
    }

//    NSLog(@"%@",paramDic);
    [SendRequest getWithURL:url params:paramDic withCookie:YES success:^(id response) {
        [SVProgressHUD dismiss];
        self.navView.rightbutton.enabled = YES;
        int code = [response[@"code"] intValue];
        NSString *message = response[@"msg"];
        if(code==0){
            NSString *tip ;
            if (self.isModify) {
                tip = @"修改成功！";
            }else{
                tip = @"提交成功！";
            }
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:tip delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }else{
            SHOWERROR(message)
        }
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        self.navView.rightbutton.enabled = YES;
        SHOWERROR(showNetworkError)
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)uploadImageWithData:(UIImage*)image withSuccessBlock:(void(^)(NSString*imageUrl))successBlock{
    
    NSString*url=[NSString stringWithFormat:@"%@/api/qiniu/meiziqntoken?publishStatus=2",URL_HOST];
    [SendRequest getWithURL:url params:nil withCookie:YES success:^(id response) {
        int code = [response[@"code"] intValue];
        NSString *message = response[@"msg"];
        if(code==0){
            NSString *token = response[@"data"][@"token"];
            NSString *domain = response[@"data"][@"domain"];
            
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            NSData *data =UIImageJPEGRepresentation(image,0.01);
            [upManager putData:data key:nil token:token
                      complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          if (info.isOK) {
                              NSString *resp_key = resp[@"key"];
                              
                              NSString *imgUrl = [NSString stringWithFormat:@"%@%@",domain,resp_key];
                              successBlock(imgUrl);
                          }else{
                              [SVProgressHUD dismiss];
                              self.navView.rightbutton.enabled = YES;
                              SHOWERROR(@"图片上传失败")
                          }
                      } option:nil];
        }else{
            [SVProgressHUD dismiss];
            self.navView.rightbutton.enabled = YES;
            SHOWERROR(message)
        }
    } fail:^(NSError *error) {
         [SVProgressHUD dismiss];
        self.navView.rightbutton.enabled = YES;
        SHOWERROR(showNetworkError)
    }];
}

@end
